package com.ykq.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author: 闫克起
 * @Description:
 * @Date: Create in 9:37 2024/10/17
 */
public class OssUtils {
    public static String ossUpload(MultipartFile myfile){
        OSS ossClient =null;
        try {
            // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
            String endpoint = "oss-cn-hangzhou.aliyuncs.com";
            //AccessKey
            String accessKey = "LTAI5tKbYAyiwqeps8ZEhL7U";
            //密钥
            String accessKeySecret = "s0FuDJBCCfM29n46dBsKwEzixlYKpq";
            // 填写Bucket名称，例如examplebucket。
            String bucketName = "qy178";
            // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
            String objectName = UUID.randomUUID().toString().replace("-", "") + myfile.getOriginalFilename();
            // 创建OSSClient实例。
            ossClient= new OSSClientBuilder().build(endpoint, accessKey, accessKeySecret);

            InputStream inputStream = myfile.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            //https://qy178.oss-cn-hangzhou.aliyuncs.com/1.jpg
            String path="https://"+bucketName+"."+endpoint+"/"+objectName;
            return path;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(ossClient!=null){
                ossClient.shutdown();
            }
        }
    }
}
